package com.suxin.http.response;


import com.suxin.http.model.Header;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author Tang
 * @classname JdkHttpClientResponse
 * @description [  ]
 * @date 2023/3/5 12:58
 */
public class JdkHttpClientResponse implements HttpClientResponse{

    HttpURLConnection urlConnection;

    Header header;

    InputStream inputStream;

    public JdkHttpClientResponse(HttpURLConnection urlConnection) {
        this.urlConnection = urlConnection;
    }

    @Override
    public Header getHeaders() {
        if (header == null) {
            header = Header.newInstance();
        }
        final Map<String, List<String>> headerFields = this.urlConnection.getHeaderFields();
        header.setOriginHeaders(headerFields);
        return header;
    }

    @Override
    public InputStream getBody() throws IOException {
        final InputStream errorStream = this.urlConnection.getErrorStream();
        final InputStream inputStream = this.urlConnection.getInputStream();
        this.inputStream = (errorStream != null) ? inputStream :errorStream;
        return this.inputStream;
    }

    @Override
    public int getStatusCode() throws IOException {
        return this.urlConnection.getResponseCode();
    }

    @Override
    public String getStatusText() throws IOException {
        return this.urlConnection.getResponseMessage();
    }

    @Override
    public void close() throws IOException {
        inputStream.close();
    }
}
